import Express from 'express';
import bookManager from '../db/bookManager';
import serviceResponder from '../helper/serviceResponder';

const router = Express.Router();

// 根据id获取单本书，详情页使用，这里用params
router.get('/:id', async (request, response) => {
    try {
        const id: string = request.params.id;
        console.log(id);
        const book = await bookManager.findById(id);
        serviceResponder.dispatchData(response, book);
    } catch (e) {
        serviceResponder.dispatchError(response, e.toString());
    }
});

// 根据分页信息查询多篇文章 这里用query
// router.get('/', async (request, response) => {
//     const result = await ArticleService.find(request.query);
//     ResponseHelper.sendPageData(result, response);
// });

// 添加书
router.post('/', async (request, response) => {
    // 这里的使用request.body需要使用中间件Express.json()
    const result = await bookManager.add(request.body);
    Array.isArray(result)
        ? serviceResponder.dispatchError(response, result)
        : serviceResponder.dispatchData(response, result);
});

// 修改书
router.put('/:id', async (request, response) => {
    try {
        const result = await bookManager.edit(request.params.id, request.body);
        Array.isArray(result)
            ? serviceResponder.dispatchError(response, result)
            : serviceResponder.dispatchData(response, result);
    } catch (e) {
        serviceResponder.dispatchError(response, e.toString());
    }
});

// 删除书
router.delete('/:id', async (request, response) => {
    try {
        await bookManager.remove(request.params.id);
        serviceResponder.dispatchData(response, null);
    } catch (e) {
        serviceResponder.dispatchError(response, e.toString());
    }
});

export default router;
